from flask import Flask, request
from flask_cors import CORS
import sqlite3
from flask import g
import os
import json

path = os.path.abspath('./backend/')
# path = '/home/hh/volun-plat/backend/'
DATABASE = os.path.join(path, 'data.sqlite3')

app = Flask(__name__)
CORS(app, supports_credentials=True)

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route("/api/getusernames", methods=['GET'])
def getusernames():
    query = "SELECT username FROM userinfo"
    result = query_db(query)
    usernames = list(map(lambda row: {'text': row[0]}, result))
    return json.dumps(usernames)

@app.route('/api/giteehook', methods=['POST'])
def hook():
    try:
        if 'X-Gitee-Token' not in request.headers:
            return 'missing X-Gitee-Token'
        os.system('bash /home/hh/volun-plat/backend/update.sh > update.log &')
        return 'ok'
    except Exception as e:
        return 'failed: {}////'.format(e)

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8087)
